package cn.picclife.mwx.manager.sys.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cn.picclife.mwx.manager.sys.mapper.QualityDataMapper;
import cn.picclife.mwx.manager.sys.mapper.SysMaintainMapper;
import cn.picclife.mwx.manager.sys.model.bo.DataCollectBo;
import cn.picclife.mwx.manager.sys.model.bo.PageCount;
import cn.picclife.mwx.manager.sys.model.bo.QueryDataCollectListRes;
import cn.picclife.mwx.manager.sys.model.bo.UpdateCollectReq;
import cn.picclife.mwx.manager.sys.model.bo.UserSessionBo;
import cn.picclife.mwx.manager.sys.model.po.DataCollect;
import cn.picclife.mwx.manager.sys.model.po.DataCollectUser;
import cn.picclife.mwx.manager.sys.model.po.SysMaintain;
import cn.picclife.mwx.manager.sys.model.po.SysmaintainVersion;
import cn.picclife.mwx.manager.sys.service.QualityDataService;
import cn.picclife.mwx.manager.util.enums.ResponseStatusEnum;

@Service
public class QualityDataServiceImpl implements QualityDataService{
	
	@Autowired
	public QualityDataMapper qualityDataMapper;
	
	
	@Autowired
	public SysMaintainMapper sysMaintainMapper;
	
	
	
	private Log log = LogFactory.getLog(QualityDataServiceImpl.class);
	
	@Override
	public PageCount queryDataList(UpdateCollectReq req) {
		PageCount pageCount = new PageCount();
		pageCount.setNowPage(req.getNowPage());//当前页
		pageCount.setRowNum(req.getRowNum());//每页多少条
		//查询总条数
		Map<String,Object> datemap = new HashMap<String,Object>();
		
		datemap.put("businessNo", req.getBusinessNo());//业务号
		datemap.put("appliName", req.getAppliName());//投保人姓名
		datemap.put("auditState", "3");//待审核
		datemap.put("id", req.getId());//待审核
		//总数
		int allCount = qualityDataMapper.queryCount(datemap);
		log.info("=====allCount==="+allCount);
		if(0==pageCount.getRowNum()) {
			pageCount.setRowNum(10);
		}
		if(0==pageCount.getNowPage()) {
			pageCount.setNowPage(1);
		}
		int allPages = allCount / pageCount.getRowNum();

		if (allCount % pageCount.getRowNum() > 0) {
			allPages += 1;//总页数
		}
		pageCount.setAllPages(allPages);
		pageCount.setAllCount(allCount);
		int minTotal = (pageCount.getNowPage() - 1) * pageCount.getRowNum();
		int maxTotal = pageCount.getNowPage() * pageCount.getRowNum();
		pageCount.setMinTotal(minTotal);
		pageCount.setMaxTotal(maxTotal);
		pageCount.setMaxminTotal(maxTotal-minTotal);
		pageCount.setObject(datemap);
		log.info("====pageCount==="+datemap.toString());
		List<DataCollect> dataCollectList = qualityDataMapper.queryDataPage(pageCount);
		log.info("++++++++列表数据+++++++"+dataCollectList);
		List<QueryDataCollectListRes> resList = new ArrayList<QueryDataCollectListRes>();
		for(DataCollect dataCollect:dataCollectList) {
			QueryDataCollectListRes res = new QueryDataCollectListRes();
			SysMaintain maintain = new SysMaintain();
			maintain.setSystemNo(dataCollect.getSysCode());
			BeanUtils.copyProperties(dataCollect, res, QueryDataCollectListRes.class);
			log.info("=====res===="+res);
			List<SysMaintain> mainList = qualityDataMapper.querySysMaintain(maintain);
			if(mainList!=null&&mainList.size()>0) {
				res.setSysName(mainList.get(0).getSystemName());//系统名称
			}
			resList.add(res);
		}
		log.info("====resList"+resList);
		pageCount.setDatas(resList);
		return pageCount;
	}
	/**
	 * 获取视频回放信息
	 */
	@Override
	public List<String> queryDataFile(UpdateCollectReq req) throws Exception {
		DataCollect bo = new DataCollect();
		bo.setId(req.getId());//数据主键id
		bo.setBusinessNo(req.getBusinessNo());//业务识别号（保单号）
		List<DataCollect> dataCollectList = qualityDataMapper.queryData(bo);
		log.info("======queryDataFile视频回放接口数据查询结果:======"+JSONObject.toJSONString(dataCollectList).toString());
		if(null==dataCollectList||dataCollectList.size()<=0) {
			return null;
		}
		DataCollect dataCollect = dataCollectList.get(0);
		if(null==dataCollect||null==dataCollect.getUploadUrl()||dataCollect.getUploadUrl().trim().length()<=0) {
			return null;
		}
		return readData(dataCollect.getUploadUrl());
	}
	/**
	 * 获取视频播放用户列表
	 */
	@Override
	public List<DataCollectUser> queryUserList(String datacollectId, HttpServletRequest request) {
		List<DataCollectUser>userList =  qualityDataMapper.queryDataCollectUser(datacollectId);
		UserSessionBo user = (UserSessionBo) request.getSession().getAttribute("user");
		log.info("==========user");
		if(null!=user&&null!=user.getOptNo()) {
			DataCollectUser dataUser = new DataCollectUser();
			dataUser.setDatacollectId(datacollectId);
			dataUser.setOptNo(user.getOptNo());
			dataUser.setDeptNo(user.getDeptNo());
			dataUser.setDeptName(user.getDeptName());
			dataUser.setDeptLevel(user.getDeptLevel());
			dataUser.setOptTime(new Date());
			int a = qualityDataMapper.saveDataCollectUser(dataUser);
			log.info("a======"+a);
		}
		return userList;
	}

	/**
	 * 获取文件内容
	 * @return
	 * @throws Exception
	 */
	public List<String> readData(String url) throws Exception {
		
		List<String> strList = new ArrayList<String>();
		if(url==null||url.trim().length()<=0) {
			return null;
		}
		File file = new File(url);
		if(!file.exists()) {
			return null;
		}
		FileInputStream fis = null;
		InputStreamReader isr = null ;
		BufferedReader br = null ;
		try {
			fis = new FileInputStream(url);
			// 防止路径乱码  eclipse里创建的txt 用gb2312
			isr = new InputStreamReader(fis, "utf-8");
			br = new BufferedReader(isr);
			String line = "";
		    while ((line = br.readLine()) != null) {
		    	log.info(line);
		    	strList.add(line);
		    }
		    br.close();
		    isr.close();
		    fis.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e);
		}finally {
			if(null!=br) {
				br.close();
			}
			if(null!=isr) {
				isr.close();
			}
			if(null!=fis) {
				fis.close();
			}
		}
		return strList;
	}
	
	/**
	 * 更新数据表t_data_collect信息
	 */
	@Override
	public int updateData(UpdateCollectReq req) {
		int updateFlag = 0;
		DataCollect dataCollect = qualityDataMapper.queryDataById(req.getId());
		if(null==dataCollect||null==dataCollect.getId()||dataCollect.getId().trim().length()<=0) {
			return updateFlag;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		DataCollect bo = new DataCollect();
		bo.setId(req.getId());//数据主键id
		bo.setBusinessNo(req.getBusinessNo());//业务识别号（保单号）
		bo.setPhoneModel(req.getPhoneModel());//手机型号
		bo.setSysCode(req.getSysCode());//系统名称
		bo.setAppliName(req.getAppliName());//投保人姓名
		bo.setAppliBirthday(req.getAppliBirthday());//投保人出生日期
		bo.setAppliCardNo(req.getAppliCardNo());//投保人证件号
		bo.setInsuredName(req.getInsuredName());//被保人姓名
		bo.setInsuredBirthday(req.getInsuredBirthday());//被保人出生日期
		bo.setInsuredCardNo(req.getInsuredCardNo());//被保人证件号
		bo.setProductName(req.getProductName());//产品名称
		bo.setProductCode(req.getProductCode());//产品编码
		bo.setTotalPremium(req.getTotalPremium());//总保费
		bo.setPolicyStatus(req.getPolicyStatus());//保单状态
		bo.setAuditState(req.getAuditState());//审核状态：0-未审核、1-审核已通过、2-审核未通过\3-审核中
		bo.setOrganCode(req.getOrganCode());//机构
		bo.setProjson(req.getProjson());//json串
		bo.setDispute_recourse(req.getDispute_recourse());//纠纷原因
		bo.setFriend_status(req.getFriend_status());//纠纷状态
		if(null!=req.getDispute_start()) {
			try {
				bo.setDispute_start(sdf.parse(req.getDispute_start()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				log.error(e);
			}//纠纷开始时间
		}
		if(null!=req.getDispute_end()) {
			try {
				bo.setDispute_end(sdf.parse(req.getDispute_end()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				log.error(e);
			}//纠纷结束时间
		}
		bo.setVersionNo(req.getVersionNo());//版本号
		updateFlag = qualityDataMapper.updateDataById(bo);
		
		//根据版本号和系统代码来查询t_sysmaintain_version是否有数据，若无数据则维护该版本
		int count = 0;
		Map<String,String> strMap = new HashMap<String, String>();
		if(1==updateFlag&&null!=dataCollect&&null!=req.getSysCode()&&req.getSysCode().trim().length()>0) {
			strMap.put("systemNo", req.getSysCode());
			String versionNo = dataCollect.getVersionNo();
			if(req.getSysCode()!=null&&req.getSysCode().trim().length()>0) {
				versionNo = req.getSysCode();
			}
			strMap.put("versionNo", versionNo);
			count = qualityDataMapper.queryBySysCodeVersion(strMap);
		}
		SysMaintain maintain = new SysMaintain();
		maintain.setSystemNo(req.getSysCode());
		List<SysMaintain>mainList = sysMaintainMapper.querySysMaintain(maintain);
		if(mainList==null||mainList.size()<=0) {
			log.info("====视频采集更新接口==未查询到系统信息==无法维护该系统版本=");
			return updateFlag;
		}
		if(count==0) {
			SysmaintainVersion version = new SysmaintainVersion();
			SysMaintain main = mainList.get(0);
			version.setSysmaintainId(main.getId());
			version.setSysversionId(UUID.randomUUID().toString());
			String versionNo = dataCollect.getVersionNo();
			if(req.getSysCode()!=null&&req.getSysCode().trim().length()>0) {
				versionNo = req.getSysCode();
			}
			version.setVersionNo(versionNo);
			version.setVersionUpdateTime(new Date());
			qualityDataMapper.saveSysMaintainVersion(version);
		}
		log.info("========updateFlag========"+updateFlag);
		return updateFlag;
	}
	@Override
	public PageCount queryAccountList(DataCollectBo bo,HttpServletRequest request) throws Exception {
		
		PageCount pageCount = new PageCount();
		pageCount.setNowPage(bo.getNowPage());//当前页
		pageCount.setRowNum(bo.getRowNum());//每页多少条
		//查询总条数
		Map<String,Object> datemap = new HashMap<String,Object>();

		UserSessionBo userSessionBo=(UserSessionBo)request.getSession().getAttribute("user");
		String deptNo = userSessionBo.getDeptNo();
		String deptLevel = userSessionBo.getDeptLevel();
		if(!"1".equals(deptLevel)){
			datemap.put("deptNo",deptNo);
		}
		datemap.put("productCode", bo.getProductCode());
		datemap.put("sysCode", bo.getSysCode());
		datemap.put("startTime", bo.getStartTime());
		datemap.put("endTime", bo.getEndTime());
		//总数
		List<DataCollect> list =qualityDataMapper.queryAccountCount(datemap);
		int allCount = list.size();
		
		log.info("=====allCount==="+allCount);
		if(0==pageCount.getRowNum()) {
			pageCount.setRowNum(10);
		}
		if(0==pageCount.getNowPage()) {
			pageCount.setNowPage(1);
		}
		int allPages = allCount / pageCount.getRowNum();

		if (allCount % pageCount.getRowNum() > 0) {
			allPages += 1;//总页数
		}
		pageCount.setAllPages(allPages);
		pageCount.setAllCount(allCount);
		int minTotal = (pageCount.getNowPage() - 1) * pageCount.getRowNum();
		int maxTotal = pageCount.getNowPage() * pageCount.getRowNum();
		pageCount.setMinTotal(minTotal);
		pageCount.setMaxTotal(maxTotal);
		pageCount.setMaxminTotal(maxTotal-minTotal);
		pageCount.setObject(datemap);
		log.info("====pageCount==="+datemap.toString());
		//根据系统和产品查询
		List<DataCollect> dataCollectList = qualityDataMapper.queryAccountByCode(pageCount);
		
		log.info("==========根据系统和产品查询结果：========"+dataCollectList.size());
		//封装返回结果
		List<DataCollect> retList = new LinkedList<>();
		for(DataCollect data : dataCollectList) {
			//根据syscode查询sysname
			SysMaintain maintain= new SysMaintain();
			maintain.setSystemNo(data.getSysCode());
			List<SysMaintain> m =sysMaintainMapper.querySysMaintain(maintain);
			data.setSysName(m.get(0).getSystemName());
			//判断录制状态
//			String state = data.getRecordState();
			String state = data.getDataState();
			log.info("===state==="+state);
			retList.add(data);
//			if("3".equals(state)) {
//				//3  录制完成状态，根据完成时间统计
//				Date recodeTime = data.getUploadTime();
//				SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
//				String time = ft.format(recodeTime);
//				boolean flag = yearMonthBetween(time,bo.getStartTime(),bo.getEndTime());
//				//判断时间是否在查询日期之内
//				if(flag) {
//					retList.add(data);
//				}
//			}else {
//				//录制未完成 ，根据上传日期统计
//				Date uploadTime = data.getUploadTime();
//				SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
//				String time = ft.format(uploadTime);
//				boolean flag = yearMonthBetween(time,bo.getStartTime(),bo.getEndTime());
//				if(flag) {
//					retList.add(data);
//				}
//			}
		}
		pageCount.setDatas(retList);
		return pageCount;
	}

	
	public static boolean yearMonthBetween(String nowDate, String startDate, String endDate) throws Exception {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Date now = format.parse(nowDate);
        Date start = format.parse(startDate);
        Date end = format.parse(endDate);

        long nowTime = now.getTime();
        long startTime = start.getTime();
        long endTime = end.getTime();

        return nowTime >= startTime && nowTime <= endTime;
    }
	@Override
	public List<SysMaintain> querySysMaintain(SysMaintain maintain,HttpServletRequest request) {
		List<SysMaintain> list = sysMaintainMapper.querySysMaintain(maintain);
		//将查询到集合进行筛选================2021/03/11
		UserSessionBo userSessionBo = (UserSessionBo) request.getSession().getAttribute("user");
		String deptNo = userSessionBo.getDeptNo();
		String level = userSessionBo.getDeptLevel();
		List<SysMaintain> list1 =new ArrayList<>();
		if("1".equals(level)){
			list1=list;
		}else{
			for (SysMaintain sysMaintain : list) {
				if (sysMaintain.getSystemNo()!=null&&sysMaintain.getSystemNo().startsWith(deptNo)){
					list1.add(sysMaintain);
				}
			}
		}
		return list1;

	}

}
